package com.kili.file.service.impl;

import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.kili.file.config.systemparam.FileUploadS3ParamConfig;
import com.kili.file.controller.request.FileUploadRequest;
import com.kili.file.service.FileUploadService;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

import java.io.InputStream;

/**
 * @author Gordon
 * @version 2019/5/28
 */
@Slf4j
@Setter
public class FileUploadWithS3CloudStorage implements FileUploadService {

    private FileUploadS3ParamConfig fileUploadS3ParamConfig;
    private AmazonS3                s3;

    @Override
    public String uploadHandler(FileUploadRequest request) {
        InputStream is;
        try {
            is = request.getFile().getInputStream();
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentLength(is.available());
            // 指定该Object被下载时的网页的缓存行为
            metadata.setCacheControl("no-cache");
            // 指定该Object下设置Header
            metadata.setHeader("Pragma", "no-cache");
            // 指定该Object被下载时的内容编码格式
            metadata.setContentEncoding("utf-8");
            s3.putObject(fileUploadS3ParamConfig.getBucketName(), request.getUrl(), is, metadata);
        } catch (Exception e) {
            throw new RuntimeException("Upload object to s3 error", e);
        }

        return request.getUrl();
    }
}
